<template>
    <h-section title="产品需求列表" collapse>
        <!-- v-if="!disabled" -->
        <a-row :gutter="24">
            <a-col :span="6">
                <a-button block type="dashed" class="add-btn" @click="handleCreate">
                    <PlusOutlined />
                    <span>新建需求</span>
                </a-button>
            </a-col>
            <a-col :span="12">
                <h-search-select-cell
                    placeholder="搜索关联产品需求"
                    style="width: 100%"
                    type="proRequire"
                    label="requireName"
                    :searchQuery="{ system: detail.requestSystem, isUp: 0 }"
                    @success="handleUpdateBatch($event, 1)"
                />
            </a-col>
        </a-row>
        <a-table rowKey="id" size="small" :columns="tableColumns" :data-source="productList" :pagination="false">
            <template #requireName="{ text }">
                <a-tooltip :title="text">
                    {{ text }}
                </a-tooltip>
            </template>
            <template #stage="{ record }"> {{ $filters.valToNameFilter('stage', record.stage) }} </template>
            <template #status="{ record }">
                <flexbox>
                    <a-badge status="success" :text="$filters.valToNameFilter('status', record.status)" />
                </flexbox>
            </template>
            <template #expectTime="{ record }">
                {{ $filters.dateFilter(record.expectTime) }}
            </template>
            <template #action="{ record }">
                <router-link :to="{ path: '/productRequire/productDetail', query: { id: record.id } }">详情</router-link>
                <div style="display: inline-block">
                    <a-divider type="vertical" />
                    <a @click="handleUpdateBatch(record, 0)">移除</a>
                </div>
                <div style="display: inline-block" v-if="record.relateVersionId || record.instanceId">
                    <a-divider type="vertical" />
                    <a @click="handleShowHistory(record)">查看历史详情</a>
                </div>
            </template>
        </a-table>
        <flexbox justify="flex-end" v-if="showTip">
            <div style="font-size: 14px" class="caption-font-color margin-t-16">
                提示： 您可以将产品需求规划到预发布版本，<router-link :to="{ path: '/version/versionList' }">新建版本点击跳转版本列表；</router-link
                ><router-link :to="{ path: '/productRequire/myRequire' }">已有版本点击跳转产品需求列表</router-link>
            </div>
        </flexbox>
        <CreateStory ref="createStoryRef" :detail="detail" @success="handleSuccess" />
        <history-modal ref="historyModalRef" />
    </h-section>
</template>

<script lang="ts">
import api from '@/api';
import filters from '@/utils/filter';
import { useMessage } from '@/hooks/common/useMessage';
import store from '@/store';
import { PlusOutlined } from '@ant-design/icons-vue';
import { HSearchSelectCell } from '@/components';
import CreateStory from '@/views/taskRequire/taskDetail/components/CreateStory.vue';
import HistoryModal from './HistoryRecord/product/index.vue';
import { message } from 'ant-design-vue';
import { computed, defineComponent, ref, unref, PropType } from 'vue';
export default defineComponent({
    name: 'RequireList',
    components: {
        PlusOutlined,
        CreateStory,
        HSearchSelectCell,
        HistoryModal
    },
    props: {
        detail: { type: Object as PropType<Recordable>, default: () => ({}) },
        disabled: {
            type: Boolean,
            default: false
        }
    },
    emits: ['success'],
    setup(props, { emit }) {
        const { createJiraLogin } = useMessage();
        const createStoryRef = ref<any>();
        const historyModalRef = ref<any>();
        const tableColumns = [
            {
                title: '需求名称',
                dataIndex: 'requireName',
                slots: { customRender: 'requireName' },
                ellipsis: true
            },
            {
                title: '阶段',
                dataIndex: 'stage',
                width: 100,
                slots: { customRender: 'stage' }
            },
            {
                title: '状态',
                dataIndex: 'status',
                width: 80,
                slots: { customRender: 'status' }
            },
            {
                title: '预计交付时间',
                dataIndex: 'expectTime',
                width: 120,
                slots: { customRender: 'expectTime' }
            },
            {
                title: '操作',
                dataIndex: '',
                key: 'action',
                width: 200,
                slots: { customRender: 'action' }
            }
        ];
        const productList = computed((): Recordable[] => {
            const { relateRequest, sonRequestInfos, pmpProductRequires, id } = props.detail;
            //是否是父需求
            if (relateRequest === 0) {
                //如果有子需求需要遍历子需求的产品需求列表
                if (sonRequestInfos && sonRequestInfos.length) {
                    return sonRequestInfos.reduce((prev, curr) => {
                        return prev.concat(curr.pmpProductRequires || []);
                    }, []);
                } else {
                    return pmpProductRequires || [];
                }
            } else {
                const target = sonRequestInfos.find((item) => item.id === id);
                return target.pmpProductRequires || [];
            }
        });

        const showTip = computed(() => {
            if (unref(productList).length) {
                return productList.value.some((item) => !item.relateVersionId);
            } else {
                return false;
            }
        });
        const validate = () => {
            return Promise.resolve(true);
        };
        // 创建需求
        const handleCreate = async () => {
            const { requestName, requestDesc: requireDesc, id, requestSystem, pmpProductDetailDTO, source } = props.detail;
            // 找出该系统默认的当前处理人
            const { success, moule } = await api.systemManagerModel.findManagersBySystem({
                catalogCode: pmpProductDetailDTO.catalogCode,
                position: '产品经理'
            });
            if (success) {
                // 自动填写默认值，需求类型，优先级，需求描述，所属系统，关联业务需求等
                let target = moule.find((item) => item.empId === store.getters.userInfo.employeeDTO.empId);
                target = target || moule[0];
                unref(createStoryRef).open({
                    requireName: requestName,
                    requireDesc,
                    requireType: filters.valToNameFilter('source', source) === '缺陷' ? '4' : '1',
                    level: '4',
                    agentUser: target.manager,
                    agentUserEmpId: target.empId,
                    relateRequireId: id,
                    relateRequireName: requestName,
                    requireSystem: +requestSystem,
                    devType: pmpProductDetailDTO.systemType !== '3' ? pmpProductDetailDTO.systemType : '2',
                    systemType: pmpProductDetailDTO.systemType
                });
            }
        };
        const handleShowHistory = async (record) => {
            if (record.relateVersionId) {
                const { success, moule, errorMsg } = await api.versionModel.findById({ id: record.relateVersionId });
                if (success) {
                    if (moule.instanceId) {
                        unref(historyModalRef).open(record);
                    } else {
                        message.error('暂无历史详情');
                    }
                } else {
                    message.error(errorMsg);
                }
            }
            if (record.instanceId) {
                unref(historyModalRef).open(record);
            }
        };
        const handleSuccess = () => {
            emit('success');
        };
        const handleUpdateBatch = async (query, type: 0 | 1) => {
            if (type) {
                if (unref(productList).find((item) => item.id === query.id)) {
                    message.error('请勿重新绑定');
                    return;
                }
                const { requestName, id } = props.detail;
                query = {
                    ...query,
                    relateRequireName: requestName,
                    relateRequireId: id,
                    businessChange: true
                };
            } else {
                query = {
                    ...query,
                    relateRequireName: null,
                    relateRequireId: null,
                    businessChange: true
                };
            }
            const { success, errorCode } = await api.productRequireModel.update(query);
            if (success) {
                handleSuccess();
            } else {
                if (errorCode === '003') {
                    createJiraLogin({
                        systemId: props.detail.requestSystem,
                        onOk() {
                            api.productRequireModel.update(query);
                        }
                    });
                    return;
                }
            }
        };
        return {
            createStoryRef,
            historyModalRef,
            tableColumns,
            productList,
            showTip,
            handleUpdateBatch,
            validate,
            handleCreate,
            handleSuccess,
            handleShowHistory
        };
    }
});
</script>
<style lang="less" scoped>
.add-btn {
    margin-bottom: 8px;
}
</style>
